package com.example.androidbrowserpro;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.androidTool.NetWorkStateReceiver;
import com.androidTool.SystemService;
import com.example.androidbrowserpro.setting.SettingDialog;
import com.zy.devicelibrary.UtilsApp;

import java.util.Timer;
import java.util.TimerTask;


public class WebViewActivity extends Activity {
    private WebView _webView;
    private String _url;
    private Timer timer;
    public NetWorkStateReceiver netWorkStateReceiver;
//
//    public DevicePolicyManager policyManager;
//    public ComponentName adminReceiver;
//    public PowerManager mPowerManager;

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        //设置屏幕长亮
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        try {
            SharedPreferences sp = getSharedPreferences("webViewSetting", Context.MODE_PRIVATE);
            _url = sp.getString("url", "file:///android_asset/index.html");
            if (_url.contains("?")) {
                _url += "&tt=" + System.currentTimeMillis();
            } else {
                _url += "?tt=" + System.currentTimeMillis();
            }

            SystemService.init(this);
            SpeechService.init(this);
            netWorkStateReceiver = new NetWorkStateReceiver();
            netWorkStateReceiver.setReceviceCallback(new NetWorkStateReceiver.ReceviceCallback() {
                @Override
                public void onResult(boolean result) {
                    if (result) {
                        _webView.loadUrl(_url);
                    }
                }
            });
            Context activityContext = getApplicationContext();
            _webView = new WebView(activityContext);
            setContentView(_webView);
            WebSettings webSettings = _webView.getSettings();
            webSettings.setJavaScriptEnabled(true);

            // 设置允许JS弹窗
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            // 通过addJavascriptInterface()将Java对象映射到JS对象
            // 参数1：JavaScript对象名，参数2：Java对象名
            // WebViewJsBridge类对象映射到JS的Android对象
            _webView.addJavascriptInterface(new WebViewJsBridge(this, _webView), "AndroidBrowser");
            //_webView.setWebViewClient(new WebViewClient());
            _webView.setWebViewClient(new MyWebViewClient());
            _webView.setWebChromeClient(new MyWebChromeClient(this));
            // REMOTE RESOURCE  http://49.234.13.30:8888/h/index.html
            _webView.loadUrl(_url);
            //_webView.loadUrl("https://www.baidu.com/");
            //_webView.loadUrl("http://127.0.0.1:28072/index.html");+
            // LOCAL RESOURCE
//        _webView.loadUrl("file:///android_asset/index.html");
            //boolean b=netWorkStateReceiver.isNetWork(getBaseContext());

//        _webView.loadUrl(_url);
            UtilsApp.init(this.getApplication());

//        int [] timeonArray = new int{8,30};
//        int [] timeoffArray = new int[]{2022,11,25,13,15};
//        int [] timeonArray = new int[]{2022,11,25,13,17};
//        boolean boo=manager.setPowerOnOff(timeonArray,timeoffArray);
            //设置上述时间将会在2018年1月10号，20:38关机，20:48开机
//        Toast.makeText(this,"设置开关机:"+boo,Toast.LENGTH_SHORT);
//        timer = new Timer(true);
//        timer.schedule(timerTask, 1000, 6000); //延时1000ms后执行，1000ms执行一次

        }catch (Exception ex){
            new Http().getHttpURLConnection(ex.getMessage());
        }
        finally {
            // 启动后台服务
            this.startService();
        }
    }
    TimerTask timerTask = new TimerTask() {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };
    private Integer s;
    private Integer v;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==1){
                Toast.makeText(WebViewActivity.this, "进来了",
                    Toast.LENGTH_LONG).show();
                //回到主线程执行结束操作
                System.out.println(s/v);
//                Log.e("=====", "结束计时");
//                boolean isSuccess=SystemService.stopApps(WebViewActivity.this,"com.zebone");
//                if(isSuccess){
//                    //timer.cancel();
//                }
//                SystemService.stopApps(WebViewActivity.this,"com.yby.queue");
            }
        }
    };
    @Override
    public void onBackPressed() {
        if (_webView.canGoBack()) {
            _webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void askPermission(){
        boolean sSRPR= ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)|
                ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        Log.e("msg",Boolean.toString(sSRPR));
        if(sSRPR){
            //begin
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
            },0);
            //end
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("onDestroy", "onDestroy");
        SpeechService.release();
    }


    public void startService(){
        startService(new Intent(WebViewActivity.this, RestartService.class));
    }
    public void stopService(){
        stopService(new Intent(WebViewActivity.this, RestartService.class));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this._webView.loadUrl("file:///android_asset/set.html");
            this._webView.clearCache(true);
            // PopupSet();
        }
        return false;
    }

    //打开设置
    public void PopupSet() {
        SettingDialog b = new SettingDialog(this, WebViewActivity.this, _webView, _url);
        b.setCancelable(false);
        b.show();
        int width = this.getResources().getDisplayMetrics().widthPixels;
        int height = this.getResources().getDisplayMetrics().heightPixels;
        int dw = width > height ? width / 2 : width;
        b.getWindow().setLayout(dw, LinearLayout.LayoutParams.WRAP_CONTENT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isOpen();
    }

    /**
     * 检测用户是否开启了超级管理员
     */
    private void isOpen() {
//        if (policyManager.isAdminActive(adminReceiver)) {//判断超级管理员是否激活
//
//            Toast.makeText(WebViewActivity.this, "设备已被激活",
//                    Toast.LENGTH_LONG).show();
//        } else {
//
//            Toast.makeText(WebViewActivity.this, "设备没有被激活",
//                    Toast.LENGTH_LONG).show();
//
//        }
    }

    //在onResume()方法注册
    @Override
    protected void onResume() {
        try {
            if (netWorkStateReceiver == null) {
                netWorkStateReceiver = new NetWorkStateReceiver();
            }
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netWorkStateReceiver, filter);
        }catch (Exception ex){}

        this.acquireWakeLock();
        super.onResume();
    }

    //onPause()方法注销
    @Override
    protected void onPause() {
        unregisterReceiver(netWorkStateReceiver);
        releaseWakeLock();
        super.onPause();
    }

    private PowerManager.WakeLock mWakeLock = null;
    private void acquireWakeLock() {
        try {
            if (mWakeLock == null) {
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(
                        PowerManager.PARTIAL_WAKE_LOCK |
                                PowerManager.ACQUIRE_CAUSES_WAKEUP,
                        this.getClass().getCanonicalName());
                mWakeLock.acquire();
            }
        }catch (Exception ex){}
    }

    private void releaseWakeLock() {
        try {
            if (mWakeLock != null) {
                mWakeLock.release();
                ///mWakeLock = null;
            }
        }catch (Exception ex){}
    }

}